import { Service } from 'egg';
import CommonUtil from '../src/decorator/commonUtil';
import { v4 } from 'uuid';


export default class Mysql extends Service {


    public async insert<T>(tableName: string, datas: Omit<T, "id" | "createTime" | "recId"> & { id?: string, createTime?: Date }, conn?: EggMySQLTransation) {
        !datas.id && (datas.id = v4());
        !datas.createTime && (datas.createTime = new Date());
        return await (conn ?? this.app.mysql).insert(tableName, CommonUtil.object2UnderLine(datas));
    }

    public async any(tableName: string, condition?: EggMySQLCondition) {
        let query = await this.app.mysql.select(tableName, {
            ...(condition ?? {}),
            columns: ['id'],
            limit: 1
        });
        return query.length > 0;
    }

    /**查询一个 */
    public async firstOrDefault<T>(tableName: string, condition?: EggMySQLCondition): Promise<T | null> {
        if (condition) {
            condition.limit = 1;
            if (condition?.where) {
                condition.where = CommonUtil.object2UnderLine(condition.where);
            }
        }
        else {
            condition = { limit: 1 };
        }
        let query = await this.app.mysql.select(tableName, condition);
        return query[0] && CommonUtil.filterUnderLine(query[0]) as any;
    }


    public async updateById<T>(tableName: string, id: string, obj: Partial<T>) {
        return await (this.app.mysql.update as any)(tableName, obj, { where: { id } });
    }

    /**获取列表 */
    public async list<T>(tableName: string, condition?: EggMySQLCondition): Promise<T[]> {
        if (condition?.where) {
            condition.where = CommonUtil.object2UnderLine(condition.where);
        }
        return (await this.app.mysql.select(tableName, condition) as any[]).map(p => CommonUtil.filterUnderLine(p)) as T[];
    }



}